package fr.univ.surveyonline.result;

import java.io.CharArrayReader;
import java.io.IOException;
import java.util.Set;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import fr.univ.surveyonline.question.FormField;

public class ResultBuilder {
	public static String getXmlFromResult(FormField f,boolean forObservers)	{
		return ResultToXML.fromFormFieldToXML(f,forObservers);
	}
	
	public static Set<ResultModel> getResultFromXML(String xml) throws IOException, SAXException {
		XMLReader saxReader = XMLReaderFactory.createXMLReader();
		ResultParser fb = new ResultParser();
		saxReader.setContentHandler(fb);

		int leng = xml.length();
		char[] cbuf = new char[leng];
		for (int i=0; i < leng;i++) {
			cbuf[i] = xml.charAt(i);
		}
		
		InputSource i = new InputSource(new CharArrayReader(cbuf));
		
		saxReader.parse(i);
		
		Set<ResultModel> f = fb.getResultModel();
		if (f == null) {
			throw new IllegalStateException("Erreur");
		}
		return f;
	}
}
